import { Component } from '@angular/core';
import { NzModalService, NzModalRef, NzNotificationService } from 'ng-zorro-antd';
import { EditCompanyComponent } from '../company-management/edit-company/edit-company.component';
import { EditSiteComponent } from './edit-site/edit-site.component';
import { ApiService } from '@srvs/api.service';

@Component({
  selector: 'site-management',
  templateUrl: './site-management.component.html',
  styles: [`
    :host ::ng-deep .card-nopd .ant-card-head {
      margin-bottom: 0;
    }
    :host ::ng-deep .card-nopd .ant-card-body {
      padding: 0;
    }
    :host ::ng-deep .title-button {
      padding: 0 4px !important;
    }
  `]
})
export class SiteManagementComponent {

  public config: any = {
    sitesLoading: false,
    badgeStyle: { backgroundColor: '#d7d7d7', color: '#ffffff', boxShadow: 'none' },
  };
  public data: any = {
    companies: [],
    sites: [],
    displaySites: []
  };
  public params: any = {
    companyId: null,
    sort: null,
    keywords: null
  };
  private debounce: any;

  constructor(
    private modalSrv: NzModalService,
    private msgSrv: NzNotificationService,
    private apiSrv: ApiService
  ) {
    const apiCompanies: string = '/api/companies';
    this.apiSrv.get(apiCompanies).subscribe(
      companies => {
        this.params.companyId = companies[0] ? companies[0].id : null;
        this.data.companies = companies;
        this.data.companies.forEach(item => item.siteCount = 0);
        this.load();
      },
      error => this.msgSrv.error('公司列表加载失败！', error.message)
    );
  }

  /**
   * 加载站点列表
   */
  public load(): void {
    const apiSites: string = this.params.keywords
      ? `/api/_search/sites?query="${this.params.keywords}"`
      : '/api/sites';
    this.config.sitesLoading = true;
    this.apiSrv.get(apiSites).subscribe(
      sites => {
        this.data.sites = sites;
        this.changeCompany(this.params.companyId);
        this.refreshSiteCountByCompany();
        this.config.sitesLoading = false;
      },
      error => this.msgSrv.error('站点列表加载异常！', error.message)
    );
  }

  /**
   * 创建公司
   */
  public createCompany(): void {
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '创建公司',
      nzContent: EditCompanyComponent,
      nzWidth: 576,
      nzMaskClosable: false,
      nzOnOk: (component: EditCompanyComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            this.data.companies = [...this.data.companies, data];
            this.msgSrv.success('创建公司成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('创建公司失败！', error.message);
            ref.getInstance().nzOkLoading = false;
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 更改选中公司
   * @param companyId 公司id
   */
  public changeCompany(companyId: number): void {
    const displaySites: any[] = SiteManagementComponent
      .sortLastModifiedTime(
        this.data.sites.filter(item => item.companyId === companyId),
        this.params.sort
      )
    this.data.displaySites = displaySites;
    this.params.companyId = companyId;
  }

  /**
   * 创建站点
   */
  public createSite(): void {
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '创建站点',
      nzContent: EditSiteComponent,
      nzComponentParams: { companies: this.data.companies },
      nzWidth: 576,
      nzMaskClosable: false,
      nzOnOk: (component: EditSiteComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            this.data.sites = [...this.data.sites, data];
            this.refreshSiteCountByCompany();
            this.changeCompany(this.params.companyId);
            this.msgSrv.success('创建站点成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('创建站点失败！', error.message);
            ref.getInstance().nzOkLoading = false;
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 更新站点数据
   * @param site 站点数据
   */
  public updateSite(site: any): void {
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '修改站点',
      nzContent: EditSiteComponent,
      nzComponentParams: { data: site, companies: this.data.companies },
      nzWidth: 576,
      nzMaskClosable: false,
      nzOnOk: (component: EditSiteComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            const index: number = this.data.sites.indexOf(site),
              sites: any[] = [...this.data.sites];
            sites[index] = data;
            this.data.sites = sites;
            this.refreshSiteCountByCompany();
            this.changeCompany(this.params.companyId);
            this.msgSrv.success('修改站点成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('修改站点失败！', error.message);
            ref.getInstance().nzOkLoading = false;
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 删除站点
   * @param site 站点数据
   */
  public deleteSite(site: any): void {
    const apiSite: string = `/api/sites/${site.id}`;
    this.apiSrv.delete(apiSite).subscribe(
      () => {
        this.data.sites = this.data.sites.filter(item => item !== site);
        this.data.displaySites = this.data.displaySites.filter(item => item !== site);
        this.refreshSiteCountByCompany();
        this.msgSrv.success('删除站点成功！', null);
      },
      error => this.msgSrv.error('删除站点失败！', error.message)
    );
  }

  /**
   * 按最后修改时间排序
   */
  public sortLastModifiedTime(): void {
    this.data.displaySites = SiteManagementComponent
      .sortLastModifiedTime(
        this.data.displaySites,
        this.params.sort
      );
  }

  /**
   * 防抖动加载站点数据
   */
  public debounceLoad(): void {
    clearTimeout(this.debounce);
    this.debounce = setTimeout(() => this.load(), 500);
  }

  /**
   * 更新公司站点统计
   */
  private refreshSiteCountByCompany(): void {
    let companyObject: any = {};
    this.data.sites.forEach(site => {
      companyObject[site.companyId] = companyObject[site.companyId] || 0;
      companyObject[site.companyId]++;
    });
    this.data.companies.forEach(item => item.siteCount = companyObject[item.id] || 0);
  }

  /**
   * 按最后修改时间排序（规则）
   * @param data 排序数据
   * @param sort 排序类型
   */
  static sortLastModifiedTime(data: any[], sort: string): any[] {
    data = [...data];
    switch (sort) {
      case 'ascend':
        data.sort((a: any, b: any) => new Date(a.lastModifiedTime).valueOf() - new Date(b.lastModifiedTime).valueOf());
        break;
      case 'descend':
        data.sort((a: any, b: any) => new Date(b.lastModifiedTime).valueOf() - new Date(a.lastModifiedTime).valueOf());
        break;
      default:
        data.sort((a: any, b: any) => a.id - b.id);
    }
    return data;
  }

}
